package com.campus.customer.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.common.utils.DistanceCalculator;
import com.campus.customer.bean.merchant.MerchantQueryParam;
import com.campus.customer.entity.Merchant;
import com.campus.customer.entity.MerchantBusinessHours;
import com.campus.customer.mapper.MerchantBusinessHoursMapper;
import com.campus.customer.mapper.MerchantMapper;
import com.campus.customer.vo.MerchantVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商户表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-02
 */
@Service
public class MerchantService extends ServiceImpl<MerchantMapper, Merchant> {
    @Autowired
    private MerchantBusinessHoursMapper merchantBusinessHoursMapper;

    public PageInfo<MerchantVo> getMerchantPage(MerchantQueryParam param) {
        PageInfo<MerchantVo> pageInfo = PageHelper.startPage(param.getPageNo(), param.getPageSize())
                .doSelectPageInfo(() -> baseMapper.getMerchantPage(param));
        
        // 为每个商户设置营业时间列表
        pageInfo.getList().stream().forEach(merchantVo -> {
            //查询商户的营业时间列表
            List<MerchantBusinessHours> businessHoursList = merchantBusinessHoursMapper.selectList(Wrappers.<MerchantBusinessHours>lambdaQuery().eq(MerchantBusinessHours::getMerchantId, merchantVo.getId()));
            merchantVo.setBusinessHoursList(businessHoursList);
        });
        
        // 当排序类型为default时，对seqNo大于0的商户进行随机排序（针对推荐的商家进行随机排序，避免排序固定导致被投诉。）
        if ("default".equals(param.getSortType())) {
            List<MerchantVo> merchantList = pageInfo.getList();
            
            // 分离seqNo > 0的商户和其他商户
            List<MerchantVo> seqNoMerchants = merchantList.stream()
                    .filter(merchant -> merchant.getSeqNo() != null && merchant.getSeqNo() > 0)
                    .collect(Collectors.toList());
            
            List<MerchantVo> otherMerchants = merchantList.stream()
                    .filter(merchant -> merchant.getSeqNo() == null || merchant.getSeqNo() <= 0)
                    .collect(Collectors.toList());
            
            // 对seqNo > 0的商户进行随机排序
            Collections.shuffle(seqNoMerchants);
            
            // 重新组合列表：随机排序的seqNo商户 + 其他商户
            merchantList.clear();
            merchantList.addAll(seqNoMerchants);
            merchantList.addAll(otherMerchants);
        }
        
        return pageInfo;
    }

    public MerchantVo getMerchantById(Integer id,Double latitude, Double longitude) {
        Merchant merchant = getById(id);
        if (merchant != null) {
            MerchantVo merchantVo = new MerchantVo();
            BeanUtil.copyProperties(merchant, merchantVo);
            if(latitude != null && longitude != null){
                merchantVo.setDistance(BigDecimal.valueOf(DistanceCalculator.calculateDistance(latitude, longitude, merchant.getLatitude().doubleValue(), merchant.getLongitude().doubleValue())));
            }
            //查询商户的营业时间列表
            List<MerchantBusinessHours> businessHoursList = merchantBusinessHoursMapper.selectList(Wrappers.<MerchantBusinessHours>lambdaQuery().eq(MerchantBusinessHours::getMerchantId, id));
            merchantVo.setBusinessHoursList(businessHoursList);
            return merchantVo;
        }
        return null;
    }

}
